$(function(){
	$('input[name="begDt"], input[name="endDt"]').datepicker({
		format: "yyyy-mm-dd",
	    todayBtn: "linked",
	    language: "zh-CN",
	    autoclose: true,
	    todayHighlight: true
	});

	var today = getDay(0);
	var yesterday = getDay(-1);
	$('input[name="begDt"]').val(yesterday);
	$('input[name="endDt"]').val(today);
});

var myApp = angular.module('myApp', [ 'ngGrid', 'ui.select2' ]);

myApp.controller('tempShipmentCtrl', function($scope, $http) {
	$("#btnc").attr("disabled", true); 
	$("#btnr").attr("disabled", true); 
	$("#btnq").attr("disabled", true);
	$("#btnp").attr("disabled", true);
	$("#open").attr("disabled", true);
	$scope.addflag=true;
	//global variable
	$scope.selectedRows = [];
	//init page item
	$scope.init = function() {
		$('input[name="planlDt"],input[name="planaDt"]').datetimepicker({
			minView: "month",
			format: "yyyy-mm-dd hh:ii",
		    todayBtn: "linked",
		    language: "zh-CN",
		    forceParse: false,
		    autoclose: true,
		    todayHighlight: true
		});
		$scope.stList = [{"id":0, "lb":"在用"},{"id":1, "lb":"停用"}];
			httpPost($http, {"url":ctx+"/constractor/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.constractorList = data.dt;
			}, function(){
				toastError("初始化承运商列表失败。");
			});
			httpPost($http, {"url":ctx+"/driver/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.driverList = data.dt;
			}, function(){
				toastError("初始化司机列表失败。");
			});
			httpPost($http, {"url":ctx+"/vehicleType/findListBy", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.vehicleTypeList = data.dt;
			}, function(){
				toastError("初始化运输工具类型列表失败。");
			});
			httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"shipmentMethod","st":0}}}, function(data){
				$scope.shipment_methodList = data.dt;
			}, function(){
				toastError("初始化运输方式列表失败。");
			});
			httpPost($http, {"url":ctx+"/client/findListByFirst", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.clientList = data.dt;
			}, function(){
				toastError("初始化客户列表失败。");
			});
			httpPost($http, {"url":ctx+"/city/findListByFirst", "data": {"ffMap":{"st":0}}}, function(data){
				$scope.cityList = data.dt;
			}, function(){
				toastError("初始化城市列表失败。");
			});
			httpPost($http, {"url":ctx+"/dict/findListBy", "data": {"ffMap":{"cd":"shipmentMethod","st":0}}}, function(data){
				$scope.cdList = data.dt;
			}, function(){
				toastError("初始化运输方式列表失败。");
			});
	};
	$scope.init();
	
	//grid
	$scope.pagingOptions = {
		pageSizes : [ 20, 50, 100 ],
		pageSize : 20,
		currentPage : 1,
		onQueryFlag : false
	};
	$scope.$watch('pagingOptions', function(newVal, oldVal) {
		if (newVal !== oldVal/* && newVal.currentPage !== oldVal.currentPage*/) {
			$scope.query();
		}
	}, true);
	
	$scope.gridOptions = {
		data : 'dt',
		totalServerItems : 'tt',
		
		columnDefs : [
		{
			field : "id",
			displayName : "ID", visible : false
		},
		{
			field : "tempshipmentId",
			displayName : "tempshipmentId", visible : false
		},
		{
			field : "legs_no",
			displayName : "分段号",width:160
		},
		{
			field : "clientName",
			displayName : "客户",width:160
		},
		{
			field : "fromAddr",
			displayName : "送货地址",width:160
		},
		{
			field : "ftranslocationName",
			displayName : "目的地",width:160
		},
		{
			field : "shipment_methodName",
			displayName : "运输方式",width:160
		},
		{
			field : "descr",
			displayName : "描述",width:160
		},
		{
			field : "quantity",
			displayName : "数量",width:160
		},
		{
			field : "weight",
			displayName : "重量",width:160
		},
		{
			field : "volume",
			displayName : "体积",width:160
		},
		{
			field : "toName",
			displayName : "收货方名称",width:160
		},
		{
			field : "ftranslocationName",
			displayName : "目的地",width:160
		},
		{
			field : "palletsum",
			displayName : "托数",width:160
		},
		{
			field : "ordertime",
			displayName : "开单时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "planltime",
			displayName : "计划发车时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		},
		{
			field : "planatime",
			displayName : "预计到达时间",width:160,
			cellFilter: "date:'yyyy-MM-dd HH:mm:ss'"
		}
		],
		enablePaging : true,
		pagingOptions : $scope.pagingOptions,
		enableCellEdit:true,
		//enableCellSelection:true,
		showSelectionCheckbox : true,
		selectedItems : $scope.selectedRows,
		plugins : [ /*new ngGridFlexibleHeightPlugin()*/ ],
		i18n: 'zh-cn', rowHeight : 20.2, footerRowHeight : 35,
		showFooter : true,
		afterSelectionChange : function(rowItem, event){
			if($scope.selectedRows.length>0){
				$scope.addflag=false;
			}else{
				$scope.addflag=true;
			}
		}
	};
	
	$scope.query = function() {
		closeModal($("#queryFormModal"));
		var requestBody = {
			pageNb : $scope.pagingOptions.currentPage,
			pageSize : $scope.pagingOptions.pageSize,
			ffMap : $scope.queryForm
		};
		setTimeout(function() {
			if($scope.queryForm==null){
				$scope.queryForm={"tempshipmentId": 0 };
				requestBody.ffMap=$scope.queryForm;
			}
			httpPost($http, {"url":ctx + '/legs/findListBy', "data":requestBody, "ifBlock":true}, function(data){
				$scope.dt = data.dt;
				$scope.tt = data.tt;	
				$scope.gridOptions.$gridScope.toggleSelectAll(false);
			}, function(errMsg){
				toastError("查询失败。" + errMsg);
			});
		}, 100);
	};
	//$scope.query();

	//utils
	$scope.onClearSelectedRows = function() {
		$scope.gridOptions.$gridScope.toggleSelectAll(false);
	};
	
	$scope.onOpenQueryFormModal = function() {
		openModal($("#queryFormModal"));
	};
	//创建配载号
	$scope.onOpenEditFormModal = function(type, id) {
		if(type=="add"){
			$scope.editForm = {};
		}
		openModal($("#editFormModal"));
	};

	
	$('#c>option').click(function(){
		$scope.initChange();
		$scope.queryForm={};
		$scope.onQuery = function(){
			$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
			$scope.pagingOptions.currentPage = 1;
			$scope.queryForm={"tempshipmentId":0};
		};
		$scope.onQuery();
		$(".p").text('');
		$(".j").text(0);
		$(".o").text(0);
		$(".s").text(0);
		$(".w").text(0);
		$(".v").text(0);
	});
	//按市内市外查找
		$scope.initChange=function(){
		$("#tree li").css("display","block");
		//$(".aa").css("display","");
		$("#tree li").remove();
		var ul=$("#tree");
		httpPost($http, {"url":ctx + '/tempShipment/findListBy',"data": {"ffMap":{"code":"未配载","vocation":$("#c").attr("value")}},"ifBlock":true}, function(data){	
			
			$scope.o=data.dt[0];
			var id=data.dt[0]['id'];
			var quantity=data.dt[0]['quantity'];
			var weight=data.dt[0]['weight'];
			var volume=data.dt[0]['volume'];
			var points=data.dt[0]['points'];
			var code=data.dt[0]['code'];	
			var li="<li id='"+id+"' style='margin-left: -20px;margin-top: 1px;'><img src='/res_oms/theme-b/imgs/e01.gif' style='width:19px;'/><a href='#' style='margin-top: -16px;display: block;margin-left: 20px;font-size: 12px;text-decoration:none;'><span class='n'></span></a></li>";
			ul.append(li);
			$(".n").text("【"+code+"】"+points+"/"+quantity+"/"+weight+"/"+volume);
			httpPost($http, {"url":ctx + '/tempShipment/findListBy',"data": {"ffMap":{"code":"配载","vocation":$("#c").attr("value")}},"ifBlock":true}, function(data){
			$scope.tempshipList=data.dt;
			var squantity=0;
			var spoints=0;
			var sweight=0;
			var svolume=0;
			for(var i=0;i<data.dt.length;i++){
			var id=data.dt[i]['id'];
			var code=data.dt[i]['code'];
			var constractorId=data.dt[i]['constractorId'];
			var carNo=data.dt[i]['vehicleCd'];
			if(carNo==null){
				carNo='';
			}
			var li;
			if(constractorId!=null){
				 li="<li id='"+id+"'><img src='/res_oms/theme-b/imgs/e03.gif' style='width:17px;margin-right: 20px;'/><a href='#' style='margin-top: -17px;display: block;margin-left: 20px;font-size: 12px;text-decoration:none;'><span class='"+id+"'></span><img src='/res_oms/theme-b/imgs/e04.gif' style='width:22px;margin-left: 7px;margin-right: 5px;'/>"+carNo+"</a></li>";
			}else{
				 li="<li id='"+id+"'><img src='/res_oms/theme-b/imgs/e03.gif' style='width:17px;margin-right: 20px;'/><a href='#' style='margin-top: -17px;display: block;margin-left: 20px;font-size: 12px;text-decoration:none;'><span class='"+id+"'></span></a></li>";
			}	
			var quantity=data.dt[i]['quantity'];
			var weight=data.dt[i]['weight'];
			var volume=data.dt[i]['volume'];
			var points=data.dt[i]['points'];			
			squantity+=quantity;
			sweight+=weight;
			svolume+=volume;
			spoints+=points;
			ul.append(li);
			$("."+id+"").text("【"+code+"】"+points+"/"+quantity+"/"+weight+"/"+volume);
			}	
			//赋值
			$("#p span").text(data.dt.length);
			spoints+=$scope.o.points;
			squantity+=$scope.o['quantity'];
			sweight+=$scope.o['weight'];
			svolume+=$scope.o['volume'];
			$("#o span").text(spoints);
			//总件数
			$("#j span").text(squantity);
			//总质量
			$("#w span").text(sweight);
			//总体积
			$("#v span").text(svolume);
			
				 $("#tree li").click(function() {
					 if($(this).css("background-color")=="rgb(255, 255, 255)"||$(this).css("background-color")=="transparent"){
							$(this).css("background","#DBEAF9");
						}else{
							$(this).css("background","#ffffff");
						}
				 }); 
			//点击选中
			$("#tree li").click(function() {
			$this=$(this);
			//获取选中的id
			var sts=[];
			$("#tree li").each(function(){
				if($(this).css("background-color")=="rgb(219, 234, 249)"){
					sts.push($(this).attr("id"));
					if($(this).find("a").find("img").length>0&&sts[0]!=$("#tree li:first").attr("id")){
						$("#btnp").attr("disabled", false); 
					}else{
						$("#btnp").attr("disabled", true); 
					};
				}else if(sts.length==0){
					$("#btnp").attr("disabled", true); 
				};
			});
			if(sts[0]!=$("#tree li:first").attr("id")&&sts.length==1){
				$("#btnc").attr("disabled", false); 
			}else{
				$("#btnc").attr("disabled", true); 
			}
			if(sts[0]!=$("#tree li:first").attr("id")&&sts.length>0){
				$("#btnq").attr("disabled", false); 
			}else{
				$("#btnq").attr("disabled", true); 
			}
			var shipmentId=null;
			//console.log(shipmentId);
			var tempshipmentId=null;
			if(sts.length==1){
				shipmentId={"tempshipmentId":sts[0]};
				tempshipmentId=sts[0];
				$("#open").attr("disabled", false); 
			}else{
				$("#open").attr("disabled", true); 
			}
			//console.log(sts);
			//查询
			$scope.onQuery = function(){
				$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
				$scope.pagingOptions.currentPage = 1;
				$scope.queryForm=shipmentId;
				if(tempshipmentId==undefined){
					tempshipmentId=null;
				}
				if(tempshipmentId!=null){
					httpGet($http, {"url":ctx+'/tempShipment/id/'+tempshipmentId, "ifBlock":true}, function(data){
						$(".id").text(data.dt['id']);
						$(".p").text(data.dt['code']);
						$(".j").text(data.dt['quantity']);
						$(".o").text(data.dt['points']);
						$(".s").text(data.dt['count']);
						$(".w").text(data.dt['weight']);
						$(".v").text(data.dt['volume']);
					});
				};
			};
			
			$scope.onFilter=function(){
				$scope.pagingOptions.onQueryFlag = !$scope.pagingOptions.onQueryFlag;
				$scope.pagingOptions.currentPage = 1;
			};
			
			//创建配载
			$scope.onSaveEditForm = function(){
				closeModal($("#editFormModal"));
				var selectedRowsId = [];
				var object=[];
				$.each($scope.selectedRows, function(idx, obj){
					selectedRowsId.push(obj.id);
					object.push($scope.selectedRows[idx]);
				});	
				tempshipmentId=$scope.selectedRows[0]['tempshipmentId'];
				httpPost($http, {"url":ctx + '/tempShipment/save', "data":object,"params":{"tempshipmentId":tempshipmentId,"code":$scope.editForm.code,"ids":selectedRowsId}, "ifBlock":true}, function(data){
					toastSuccess("保存成功");
					shipmentId={"tempshipmentId":tempshipmentId};
					$(".j").text(data.dt['quantity']);
					$(".v").text(data.dt['volume']);
					$(".w").text(data.dt['weight']);
					$(".o").text(data.dt['points']);
					$(".s").text(data.dt['count']);
					$scope.initChange();
					$scope.onQuery();	
				}, function(errMsg){
					toastError("保存失败。" + errMsg);
				});
			};
			//取消配载
			$scope.cancel=function(){
				//获取值
				httpPost($http, {"url":ctx +'/tempShipment/findByIds', "params":{"ids":sts}, "ifBlock":true}, function(data){	
					if($.inArray($('.id').text(), sts)==0){
						tempshipmentId=null;
						$(".p").text($('.p').text());
						$(".o").text(0);
						$(".j").text(0);
						$(".w").text(0);
						$(".v").text(0);
						$(".s").text(0);
					}else if($.inArray($('.id').text(), sts)==-1){
						tempshipmentId=$('.id').text();
						shipmentId={"tempshipmentId":tempshipmentId};
					}
					$scope.initChange();
					$scope.onQuery();
				});
			};		
			//登记配车
			$scope.onOpenEditFormModal1 = function() {
				if($this.find("a").find("img").length==0){
					$scope.editForm1 = {};
					$scope.editForm1.driverId = '';
					if($scope.editForm1.expense==undefined){
						$scope.editForm1.expense=0;
					}
					var date= (new Date());
					var now = date.getFullYear() + "-" + (parseInt(date.getMonth()) + 1) +"-"+((date.getDate() > 9) ? date.getDate() : "0" + date.getDate())+" "+((date.getHours()> 9) ? date.getHours() : "0" + date.getHours())+":"+((date.getMinutes() > 9) ? date.getMinutes() : "0" + date.getMinutes());
					$scope.editForm1.planlDt=now;
					$scope.editForm1.shipment_method='TRUCK';
					$("#e").change(function(){
						var id=$scope.editForm1.constractorId;
						httpGet($http, {"url":ctx+'/constractor/id/'+id, "ifBlock":true}, function(data){	
							$scope.editForm1.name=data.dt['name'];
							httpPost($http, {"url":ctx+"/vehicle/findListBy", "data": {"ffMap":{"constractorId":id,"st":0}}}, function(data){
								$scope.vehicleList = data.dt;				
							}, function(){
								toastError("初始化运输工具列表失败。");
							});
						});	
					});
						$("#vh").click(function(){
							var vid=$scope.editForm1.vehicleId;
							httpGet($http, {"url":ctx+'/vehicle/id/'+vid, "ifBlock":true}, function(data){
								$scope.editForm1.vehicleNo=data.dt['vehicleNo'];
								$scope.editForm1.vehicleTypeId=data.dt['vehicleTypeId'];
								$scope.editForm1.driverId=data.dt['driverId'];
							}, function(){
								toastError("初始化运输工具列表失败。");
							});
						});
				}else{
					httpGet($http, {"url":ctx+'/tempShipment/id/'+tempshipmentId, "ifBlock":true}, function(data){
						$scope.editForm1 = data.dt;
						if($scope.editForm1.planaDt!=null){
							$scope.editForm1.planaDt = date2Ymdhms(data.dt.planaDt);
						}
						if($scope.editForm1.planlDt!=null){
							$scope.editForm1.planlDt = date2Ymdhms(data.dt.planlDt);
						}
						if($scope.editForm1.driverId ==null){
							$scope.editForm1.driverId='';
						}
						httpPost($http, {"url":ctx+"/vehicle/findListBy", "data": {"ffMap":{"constractorId":$scope.editForm1.constractorId,"st":0}}}, function(data){
							$scope.vehicleList = data.dt;				
						}, function(){
							toastError("初始化运输工具列表失败。");
						});
						$("#vh").change(function(){
							var vid=$scope.editForm1.vehicleId;
							httpGet($http, {"url":ctx+'/vehicle/id/'+vid, "ifBlock":true}, function(data){
								$scope.editForm1.vehicleNo=data.dt['vehicleNo'];
								$scope.editForm1.vehicleTypeId=data.dt['vehicleTypeId'];
							}, function(){
								toastError("初始化运输工具列表失败。");
							});
						});
					}, function(errMsg){
						toastWarning("查询此笔记录失败。");
					});
				};
				openModal($("#editFormModal1"));
			};
			
				//登记配车
				$scope.onSave=function(){
					closeModal($("#editFormModal1"));
					if($scope.editForm1.planaDt!=undefined){
						$scope.editForm1.planaDt = ymdhms2date($scope.editForm1.planaDt);
					}else{
						$scope.editForm1.planaDt=null;
					}
					if($scope.editForm1.planlDt!=undefined){
						$scope.editForm1.planlDt = ymdhms2date($scope.editForm1.planlDt);		
					}else{
						$scope.editForm1.planlDt=null;
					}
					$scope.editForm1.id=$this.attr('id');
					httpPost($http, {"url":ctx + '/tempShipment/updStByIds', "data":$scope.editForm1,"ifBlock":true}, function(data){
						$scope.initChange();
					}, function(){
						toastError("更新此笔纪录失败");
					});
				};
				//确认配载
				$scope.confirmp=function(){
					//获取当前选择的tempshipment的值
					httpPost($http, {"url":ctx +'/tempShipment/findByIds', "params":{"ids":sts}, "ifBlock":true}, function(data){	
						for(var i=0;i<data.dt.length;i++){
							var id=sts[i];
							//更新legs
							httpPost($http, {"url":ctx + '/legs/updByTempShipmentId', "params":{"tempShipmentId":sts[i],"constractorId":data.dt[i]['constractorId'],"shipment_method":data.dt[i]['shipment_method'],"st":"shipmentEd"}, "ifBlock":true}, function(data){				
							}, function(){
								toastError("更新此笔纪录失败");
							});
							$scope.editForm={};
							$scope.editForm.tempShipmentId=data.dt[i]['id'];
							$scope.editForm.constractorId=data.dt[i]['constractorId'];
							$scope.editForm.vehicleId=data.dt[i]['vehicleId'];
							$scope.editForm.expense=data.dt[i]['expense'];
							$scope.editForm.shipment_method=data.dt[i]['shipment_method'];
							$scope.editForm.quantity=data.dt[i]['quantity'];
							$scope.editForm.weight=data.dt[i]['weight'];
							$scope.editForm.volume=data.dt[i]['volume'];
							$scope.editForm.driverId=data.dt[i]['driverId'];
							$scope.editForm.points=data.dt[i]['count'];
							$scope.editForm.vocationType=data.dt[i]['vocationType'];
							$scope.editForm.planltime=data.dt[i]['planlDt'];
							$scope.editForm.planatime=data.dt[i]['planaDt'];
							//生成调度单
							httpPost($http, {"url":ctx + '/shipment/save', "data":$scope.editForm, "ifBlock":true}, function(data){
								httpPost($http, {"url":ctx + '/legs/updShipmentId', "params":{"tempShipmentId":id,"shipmentId":data.dt[0]}, "ifBlock":true}, function(data){				
									}, function(){
										toastError("更新此笔纪录失败");
									});
									toastSuccess("保存成功");				
								}, function(errMsg){
									toastError("保存失败,您输入的信息有误，请检查正确之后再保存。" + errMsg);
								});
						}
						httpPost($http, {"url":ctx+'/tempShipment/delById/',"params":{"ids":sts}, "ifBlock":true}, function(data){
							$scope.initChange();
						});						
						}, function(errMsg){
							toastWarning("查询此笔记录失败。");		
						});
					};
				});
			});
		});
		};
});